from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.executors.pool import ThreadPoolExecutor
from typing import Callable

from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.interval import IntervalTrigger

from ctaf_core.ctaf_resources.ctaf_settings import CTAFsettings


class QuartzScheduler:

    def __init__(self):
        thread_pool_size: int = CTAFsettings.get_setting("quartzSchedulerThreadPoolSize")
        executors = {'default': ThreadPoolExecutor(thread_pool_size)}
        self.scheduler = BackgroundScheduler(executors=executors)

    def start(self)-> None:
        self.scheduler.start()

    # 按照cron表达式触发执行任务
    def submit_cron_task(self, execute_task: Callable, trigger: CronTrigger):
        self.scheduler.add_job(execute_task, trigger=trigger)

    #每隔一段时间执行一个任务
    def submit_interval_task(self, execute_task: Callable, trigger: IntervalTrigger):
        self.scheduler.add_job(execute_task, trigger=trigger)

class QuartzSchedulerFactory:
    __quartz_scheduler_instance = None

    @staticmethod
    def get_quartz_scheduler() -> QuartzScheduler:
        if QuartzSchedulerFactory.__quartz_scheduler_instance is None:
            QuartzSchedulerFactory.__quartz_scheduler_instance = QuartzScheduler()
        return QuartzSchedulerFactory.__quartz_scheduler_instance